package com.example.playbox

import android.app.AlertDialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import android.widget.Toast
import com.example.playbox.bean.Game

class CustomAdapter(
    private var context: Context,
    private var data: MutableList<Map<String, Any>>,
    private val reservationListener: OnGameReservationListener
) : BaseAdapter() {

    interface OnGameReservationListener {
        fun onGameReservationUpdated(game: Game, reserved: Boolean, callback: (Boolean) -> Unit)
    }

    private val inflater: LayoutInflater = LayoutInflater.from(context)

    override fun getCount(): Int = data.size

    override fun getItem(position: Int): Any = data[position]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view: View
        val viewHolder: ViewHolder

        if (convertView == null) {
            view = inflater.inflate(R.layout.item_list, parent, false)
            viewHolder = ViewHolder(view)
            view.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as ViewHolder
        }

        val item = data[position]
        viewHolder.gameId.text = item["gameId"] as String
        viewHolder.gameName.text = item["gameName"] as String
        viewHolder.gameTime.text = item["gameTime"] as String
        viewHolder.gameNote.text = item["gameNote"] as String

        val reserved = item["reserved"] as Boolean
        if (reserved) {
            view.setBackgroundColor(context.resources.getColor(R.color.red))
        } else {
            view.setBackgroundColor(context.resources.getColor(R.color.blue))
        }

        view.setOnClickListener {
            showReservationDialog(position, reserved)
        }

        return view
    }

    fun updateData(newData: MutableList<Map<String, Any>>) {
        data = newData
        notifyDataSetChanged()
    }

    private fun showReservationDialog(position: Int, reserved: Boolean) {
        val message = if (reserved) "是否取消预约此项？" else "是否预约此项？"
        AlertDialog.Builder(context)
            .setTitle("预约")
            .setMessage(message)
            .setPositiveButton("是") { _, _ ->
                val updatedItem = data[position].toMutableMap()
                updatedItem["reserved"] = !reserved
                data[position] = updatedItem
                notifyDataSetChanged()

                val gameId = updatedItem["gameId"].toString().trim()
                val gameName = updatedItem["gameName"].toString().trim()
                val gameTime = updatedItem["gameTime"].toString().trim()
                val gameNote = updatedItem["gameNote"].toString().trim()
                val userName = updatedItem["userName"].toString().trim()

                if (gameId.isNotEmpty() && gameName.isNotEmpty() && gameTime.isNotEmpty() &&
                    gameNote.isNotEmpty() && userName.isNotEmpty()) {
                    val game = Game(gameId, gameName, gameTime, gameNote, userName, !reserved)
                    val gamepackages = mapOf(
                        "和平精英" to "com.tencent.tmgp.pubgmhd",
                        "原神" to "com.miHoyo.Yuanshen",
                        "王者荣耀" to "com.tencent.tmgp.sgame"
                    )
                    // 通知Activity或ViewModel更新数据库
                    reservationListener.onGameReservationUpdated(game, !reserved) { success: Boolean ->
                        if (success && !reserved) {
                            //写一个游戏数组
                            val pn = gamepackages[gameName].toString()
                            val launchIntent = context.packageManager.getLaunchIntentForPackage(pn)
                            if (launchIntent != null) {
                                context.startActivity(launchIntent)
                            } else {
                                Toast.makeText(context, "无法启动游戏", Toast.LENGTH_SHORT).show()
                            }
                        } else if (!success) {
                            Toast.makeText(context, "预约更新失败", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
            .setNegativeButton("否", null)
            .show()
    }

    private class ViewHolder(view: View) {
        val gameId: TextView = view.findViewById(R.id.tv_lst_gameid)
        val gameName: TextView = view.findViewById(R.id.tv_lst_gamename)
        val gameTime: TextView = view.findViewById(R.id.tv_lst_gametime)
        val gameNote: TextView = view.findViewById(R.id.tv_lst_gamenote)
    }
}